/*
 * @Author: ljk
 * @Date: 2023-05-12 19:05:04
 * @LastEditors: ljk
 * @LastEditTime: 2023-06-07 21:28:11
 * @Description: 命令行小程序统计单词个数
 */
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
using namespace std;

#define NUM 1024

int main(int argc, char* argv[])
{
    char *filename = argv[2];
    umask(0);
    int fd = open(filename, O_RDONLY, 0666);
    char buffer[NUM];
    ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
    if (n > 0)
    {
        buffer[n] = '\0';
        if (strcmp(argv[1], "-c") == 0)
        {
            cout << "字符数: " << n << endl;
        }
        else if (strcmp(argv[1], "-w") == 0)
        {
            const char* split = " ";
            char* p = strtok(buffer, split);
            int num = 0;
            while (p)
            {
                num++;
                p = strtok(NULL, split);
            }
            cout << "单词数: " << num << endl;
        }
    }
}